1220E - Tourism - CodeForces Solution


dfs and similar dp dsu graphs greedy trees *2200

Please click on ads to support us..

Python Code:

import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

n, m = map(int, input().split())
w = [0] + list(map(int, input().split()))
G = [[] for _ in range(n + 1)]
for _ in range(m):
    u, v = map(int, input().split())
    G[u].append(v)
    G[v].append(u)
s = int(input())
cnt = [len(g) for g in G]
q, k = [], 0
dp = [0] * (n + 1)
for i in range(1, n + 1):
    if cnt[i] == 1 and i ^ s:
        q.append(i)
ans = sum(w)
while len(q) ^ k:
    i = q[k]
    ma = 0
    for j in G[i]:
        ma = max(ma, dp[j])
    dp[i] = w[i] + ma
    ans -= w[i]
    for j in G[i]:
        cnt[j] -= 1
        if cnt[j] == 1 and j ^ s:
            q.append(j)
    k += 1
ans += max(dp)
print(ans)

C++ Code:

// [ нvмegy ]
// OLPCHUYENTIN2023 GOTOHUE
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
 
#define int long long
#define all(c) c.begin(), c.end()
#ifdef hvmegy
#define dbg(...) logger(#__VA_ARGS__, __VA_ARGS__)
template<typename ...Args>
void logger(string vars, Args&&... values) {
	cerr << "[" << vars << " : ";
	string delim = "";
	(..., (cerr << delim << values, delim = ", "));
	cerr << "]" << '\n'; 
}
#else
#define dbg(...)
#endif
 
mt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());
 
int GOTOHUE();
 
int32_t main()
{
        cin.tie(0) -> sync_with_stdio(0); 
        cout << fixed << setprecision(15);
	#ifdef hvmegy
		freopen("input.txt", "r", stdin); 
		freopen("output.txt", "w", stdout); 
		freopen("log.txt", "w", stderr);
	#endif
        bool MULTITEST = 0; 
        int OLPCHUYENTIN2023 = 1; 
        if (MULTITEST) cin >> OLPCHUYENTIN2023; 
	for (int i = 1; i <= OLPCHUYENTIN2023; i++) {
		if (GOTOHUE()) break;
		#ifdef hvmegy
			cout << "--ENDTEST--" << '\n';
		#endif
	}
	#ifdef hvmegy
		cerr << '\n' << clock() * 1000.0 / CLOCKS_PER_SEC << "ms" << '\n';
	#endif
        return 0;
}

int GOTOHUE() {
	
	int n, m; 
	cin >> n >> m; 
	vector<int> a(n + 1); 
	for (int i = 1; i <= n; i++) { 
		cin >> a[i]; 
	}

	vector<vector<int>> adj(n + 1); 
	for (int i = 1; i <= m; i++) { 
		int u, v; 
		cin >> u >> v; 
		adj[u].push_back(v); 
		adj[v].push_back(u); 
	}

	int s; 
	cin >> s; 

	vector<bool> vis(n + 1); 
	int ans = 0; 
	auto dfs = [&](auto self, int u, int p) -> bool { 
		int res = 0; 
		vis[u] = true; 
		for (int v : adj[u]) { 
			if (v == p) continue; 
			if (vis[v]) { 
				res |= 1; 
			}
			else { 
				res |= self(self, v, u); 
			}
		}
		if (res) { 
			ans += a[u]; 
			a[u] = 0; 
		}
		return res; 
	};

	dfs(dfs, s, s); 

	vector<int> dp(n + 1); 
	for (int i = 1; i <= n; i++) { 
		vis[i] = false; 
	}
	
	auto dfsdp = [&](auto self, int u, int p) -> void { 
		vis[u] = true; 
		dp[u] = a[u]; 
		for (int v : adj[u]) { 
			if (v == p) continue; 
			if (vis[v]) continue; 
			self(self, v, u); 
			dp[u] = max(dp[u], a[u] + dp[v]); 
		}
	};

	dfsdp(dfsdp, s, s); 

	cout << ans + dp[s]; 
	return 0; 
}


Comments

Submit
0 Comments
More Questions

1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence
42. Trapping Rain Water
32. Longest Valid Parentheses
Cutting a material
Bubble Sort
Number of triangles
AND path in a binary tree
Factorial equations
Removal of vertices
Happy segments
Cyclic shifts
Zoos
Build a graph
Almost correct bracket sequence
Count of integers
Differences of the permutations
Doctor's Secret
Back to School
I am Easy
Teddy and Tweety
Partitioning binary strings